package com.tzy.for10evalue.common.restTemplate;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

@Slf4j
public class RestTemplateLogHttpInterceptor implements ClientHttpRequestInterceptor {
    final static Logger logger = LoggerFactory.getLogger(RestTemplateLogHttpInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        Long start = System.currentTimeMillis();
        String RequestBody = new String(body, "UTF-8") ;
        logger.info("URL={},Method={},Headers={},Request body={}",request.getURI(),request.getMethod(),request.getHeaders(),RequestBody);
        ClientHttpResponse response = execution.execute(request, body);
        Long end = System.currentTimeMillis();
        logger.info("cost(ms)={},URL={},ResponseStatus={},Response body={}", (end - start),request.getURI(),response.getStatusCode(), IOUtils.toString(response.getBody(), "UTF-8"));
        return response;
    }
}